<template>
  <div v-if="weldboxDialogVisible" class="custom-dialog" v-dialog-drag>
    <!-- 头部 -->
    <div class="dialog-header">
      <span>接续盒熔接({{ nowFeatureObj.properties.CODE }})</span>
      <i class="el-icon-close" @click="handleClose"></i>
    </div>

    <div class="dialog-body">
      <div class="weld-container">
        <!-- 可用光缆列表 -->
        <div class="available-cables">
          <div class="section-title">可用光缆</div>
          <div class="cable-list">
            <div 
              v-for="cable in availableCables" 
              :key="cable.properties.SMID"
              class="cable-item"
              :class="{ 'is-selected': selectedCables.includes(cable) }"
              @click="locateCable(cable, true)"
            >
              <span class="cable-id">{{ cable.properties.CODE }}</span>
              <span class="cable-name">{{ cable.properties.NAME }}</span>
            </div>
          </div>
        </div>

        <!-- 操作按钮区 -->
        <div class="operation-buttons">
          <div class="button-group">
            <el-button 
              class="transfer-btn"
              type="primary" 
              plain
              size="mini"
              :disabled="!selectedCables.length"
              @click="addToFront"
            >
              前端光缆 <i class="el-icon-arrow-down" />
            </el-button>
            <el-button 
              class="transfer-btn"
              type="primary" 
              plain
              size="mini"
              style="margin-left: 0"
              :disabled="!selectedCables.length"
              @click="addToBack"
            >
              后端光缆 <i class="el-icon-arrow-down" />
            </el-button>
          </div>
        </div>

        <!-- 已选光缆区域 -->
        <div class="selected-cables">
          <!-- 前端光缆 -->
          <div class="cable-section">
            <div class="section-title">前端光缆</div>
            <div class="cable-list" @dragover.prevent @drop="handleDrop($event, 'front')">
              <div 
                v-for="(cable, index) in frontCables" 
                :key="cable.properties.SMID"
                class="cable-item"
                draggable="true"
                @click="locateCable(cable)"
                @dragstart="handleDragStart($event, cable, 'front', index)"
                @dragenter.prevent
                @dragover.prevent
              >
                <span :title="cable.properties.CODE" class="cable-id">{{ cable.properties.CODE }}</span>
                <span :title="cable.properties.NAME" class="cable-name">{{ cable.properties.NAME }}</span>
                <i class="el-icon-delete" @click.stop="removeFromFront(cable)" />
              </div>
            </div>
          </div>

          <!-- 后端光缆 -->
          <div class="cable-section">
            <div class="section-title">后端光缆</div>
            <div class="cable-list" @dragover.prevent @drop="handleDrop($event, 'back')">
              <div 
                v-for="(cable, index) in backCables" 
                :key="cable.properties.SMID"
                class="cable-item"
                draggable="true"
                @click="locateCable(cable)"
                @dragstart="handleDragStart($event, cable, 'back', index)"
                @dragenter.prevent
                @dragover.prevent
              >
                <span :title="cable.properties.CODE" class="cable-id">{{ cable.properties.CODE }}</span>
                <span :title="cable.properties.NAME" class="cable-name">{{ cable.properties.NAME }}</span>
                <i class="el-icon-delete" @click.stop="removeFromBack(cable)" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="dialog-footer">
      <el-button size="mini" @click="handleClose">取消</el-button>
      <el-button size="mini" type="danger" @click="handleDelete" v-if="existingData">删除熔接</el-button>
      <el-button size="mini" type="primary" @click="handleSave">打开熔接</el-button>
    </div>
  </div>
</template>

<script>
import L from '@/libs/leaflet'
import { mapObj, highlightStyle } from '@/widgets/mapUtils'
import { isArray } from 'lodash'
import { sessionStorage } from '@/deps/utils'
import { getWeldingApi, deleteWeldingApi, updateWeldinglineApi } from '@/deps/apis/weldboxApi'

export default {
  name: 'WeldboxDialog',
  data() {
    return {
      nowFeatureObj: null,
      weldboxDialogVisible: false,
      selectedCables: [],
      frontCables: [],
      backCables: [],
      usedCableIds: new Set(),
      allCables: [],
      existingData: false,
      highlightLayer: null,
      dragState: {
        item: null,
        sourceList: null,
        sourceIndex: -1
      }
    }
  },
  computed: {
    availableCables() {
      const cables = isArray(this.allCables) ? this.allCables : [];
      return cables.filter(cable => {
        // 确保cable对象有效
        if (!cable || !cable.properties || !cable.properties.SMID) {
          return false;
        }

        const cableId = cable.properties.SMID;

        // 检查是否在前端或后端光缆中
        const isInFront = this.frontCables.some(fc => fc.properties.SMID === cableId);
        const isInBack = this.backCables.some(bc => bc.properties.SMID === cableId);

        // 只返回未被使用的光缆
        return !isInFront && !isInBack;
      });
    }
  },
  beforeDestroy() {
    this.weldboxDialogVisible = false
    // 清理高亮图层
    if (this.highlightLayer) {
      mapObj.removeLayer(this.highlightLayer)
      this.highlightLayer = null
    }
  },
  methods: {
    async setWeldboxData({allLine, beforelinesInfos, afterlinesInfos, nowFeatureObj}) {
      // 重置所有状态
      this.frontCables = []
      this.backCables = []
      this.selectedCables = []
      this.usedCableIds.clear()
      this.nowFeatureObj = nowFeatureObj

      // 确保 allLine 是数组
      this.allCables = allLine ? JSON.parse(JSON.stringify(allLine)) : [];

      // 确保 beforelinesInfos 和 afterlinesInfos 是数组
      const beforeLines = isArray(beforelinesInfos) ? JSON.parse(JSON.stringify(beforelinesInfos)) : [];
      const afterLines = isArray(afterlinesInfos) ? JSON.parse(JSON.stringify(afterlinesInfos)) : [];

      // 检查是否存在熔接关系
      if (this.nowFeatureObj && this.nowFeatureObj.properties) {
        try {
          const res = await getWeldingApi({
            smid: this.nowFeatureObj.properties.SMID
          })
          this.existingData = res.success
        } catch (error) {
          console.error('获取熔接状态失败:', error)
          this.existingData = false
        }
      }

      this.frontCables = beforeLines;
      this.backCables = afterLines;

      // 更新已使用ID集合
      this.updateUsedCableIds();

      this.weldboxDialogVisible = true;
    },

    updateUsedCableIds() {
      this.usedCableIds.clear();
      // 收集所有已使用的ID
      const usedIds = new Set([
        ...this.frontCables.map(c => c.properties.SMID),
        ...this.backCables.map(c => c.properties.SMID)
      ].filter(Boolean)); // 过滤掉无效值

      // 更新已使用ID集合
      this.usedCableIds = usedIds;
    },

    handleClick(cable) {
      // 单选逻辑
      this.selectedCables = [cable]
    },

    toggleSelection(cable) {
      this.selectedCables = [cable]
    },

    handleCheckboxChange(checked, cable) {
      if (checked) {
        this.selectedCables = [cable]
      } else {
        this.selectedCables = []
      }
    },

    addToFront() {
      if (!this.selectedCables.length) return

      const cable = this.selectedCables[0]
      // 检查是否已存在
      if (!this.frontCables.some(c => c.properties.SMID === cable.properties.SMID)) {
        // 创建新对象以避免引用问题
        const newCable = JSON.parse(JSON.stringify(cable))
        this.frontCables = [...this.frontCables, newCable]
        this.usedCableIds.add(newCable.properties.SMID)
      }
      this.selectedCables = []
    },

    addToBack() {
      if (!this.selectedCables.length) return

      const cable = this.selectedCables[0]
      // 检查是否已存在
      if (!this.backCables.some(c => c.properties.SMID === cable.properties.SMID)) {
        // 创建新对象以避免引用问题
        const newCable = JSON.parse(JSON.stringify(cable))
        this.backCables = [...this.backCables, newCable]
        this.usedCableIds.add(newCable.properties.SMID)
      }
      this.selectedCables = []
    },

    removeFromFront(cable) {
      const index = this.frontCables.findIndex(c => c.properties.SMID === cable.properties.SMID)
      if (index > -1) {
        const newCables = [...this.frontCables]
        newCables.splice(index, 1)
        this.frontCables = newCables
        this.usedCableIds.delete(cable.properties.SMID)

        // 检查是否还在后端光缆中
        if (!this.backCables.some(c => c.properties.SMID === cable.properties.SMID)) {
          // 确保从 Set 中移除
          this.usedCableIds.delete(cable.properties.SMID)
        }
      }
    },

    removeFromBack(cable) {
      const index = this.backCables.findIndex(c => c.properties.SMID === cable.properties.SMID)
      if (index > -1) {
        const newCables = [...this.backCables]
        newCables.splice(index, 1)
        this.backCables = newCables
        this.usedCableIds.delete(cable.properties.SMID)

        // 检查是否还在前端光缆中
        if (!this.frontCables.some(c => c.properties.SMID === cable.properties.SMID)) {
          // 确保从 Set 中移除
          this.usedCableIds.delete(cable.properties.SMID)
        }
      }
    },

    async handleSave() {
      if (!this.frontCables.length || !this.backCables.length) {
        this.$message.warning('请选择前端和后端光缆')
        return
      }
      const userData = sessionStorage('userData')
      const data = {
        rootid: 2,
        smid: this.nowFeatureObj.properties.SMID,
        weldbox: `${this.frontCables.map(item => item.properties.SMID).join(',')};${this.backCables.map(item => item.properties.SMID).join(',')}`,
        userName: userData.userName
      }
      const res = await updateWeldinglineApi(data)
      console.error(res, 'res')
      if (!res.success) {
        this.$message.error(res.message || '打开熔接失败，请重试！')
        return
      }
      // 存储 featureData
      sessionStorage('weldbox_feature', this.nowFeatureObj)
      this.$bus.$emit('switch-component', {
        name: 'weldbox',
        title: `熔接设计(${this.nowFeatureObj.properties.CODE})`,
        path: '/weldbox'
      })
      this.handleClose()
    },

    handleDelete() {
      this.$confirm('删除后需要在熔接页面重新连接，确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 使用 nowFeatureObj 的 SMID
          const smid = this.nowFeatureObj && this.nowFeatureObj.properties ? this.nowFeatureObj.properties.SMID : null
          if (!smid) {
            this.$message.error('无效的熔接数据')
            return
          }

          const res = await deleteWeldingApi({ smid })
          if (res.success) {
            this.$message.success('删除成功')

            // 将已选择的光缆移回可用列表
            this.frontCables = []
            this.backCables = []
            this.usedCableIds.clear()
          } else {
            this.$message.error('删除失败')
          }
        } catch (error) {
          console.error('删除熔接关系失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {
        // 取消删除，不做任何操作
      })
    },

    handleClose() {
      this.$emit('closeWeldboxDialog')
      this.weldboxDialogVisible = false
      this.frontCables = []
      this.backCables = []
      this.selectedCables = []
      this.usedCableIds.clear()
      this.dragState = {
        item: null,
        sourceList: null,
        sourceIndex: -1
      }
      // 清理高亮图层
      if (this.highlightLayer) {
        mapObj.removeLayer(this.highlightLayer)
        this.highlightLayer = null
      }
    },

    // 定位到光缆
    locateCable(cable, isSelected = false) {
      // 选中当前光缆
      if (isSelected) {
        this.selectedCables = [cable]
      }

      // 清除之前的高亮
      if (this.highlightLayer) {
        mapObj.removeLayer(this.highlightLayer)
      }

      // 创建高亮图层并置顶
      this.highlightLayer = L.geoJSON(cable, {
        style: highlightStyle
      })
      this.highlightLayer.addTo(mapObj)
      this.highlightLayer.bringToFront()  // 确保图层置顶
      cable.properties.LAYERNAME = 'C_PRO_OPTLINE'
      this.$bus.$emit('CHANGE_LAYER_INFO', {...cable})
    },

    handleDragStart(event, cable, sourceList, sourceIndex) {
      // 创建新对象以避免引用问题
      this.dragState = {
        item: JSON.parse(JSON.stringify(cable)),
        sourceList,
        sourceIndex
      }
      // 设置拖拽时的透明度
      event.target.style.opacity = '0.4'
      // 添加拖拽样式
      event.target.classList.add('dragging')
    },

    handleDrop(event, targetList) {
      event.preventDefault()

      // 清除所有拖拽相关样式
      const draggingElement = document.querySelector('.dragging')
      if (draggingElement) {
        draggingElement.style.opacity = '1'
        draggingElement.classList.remove('dragging')
      }

      const { item, sourceList, sourceIndex } = this.dragState
      if (!item) return

      // 如果是在同一个列表内拖拽
      if (sourceList === targetList) {
        const targetArray = sourceList === 'front' ? [...this.frontCables] : [...this.backCables]
        // 获取拖放位置的索引
        const dropIndex = this.getDropIndex(event, targetList)

        // 重新排序
        targetArray.splice(sourceIndex, 1)
        targetArray.splice(dropIndex, 0, JSON.parse(JSON.stringify(item)))

        // 更新数组
        if (sourceList === 'front') {
          this.frontCables = targetArray
        } else {
          this.backCables = targetArray
        }
      }

      // 重置拖拽状态
      this.dragState = {
        item: null,
        sourceList: null,
        sourceIndex: -1
      }
    },

    getDropIndex(event, listType) {
      const list = listType === 'front' ? this.frontCables : this.backCables
      const items = Array.from(event.currentTarget.children)
      const draggedRect = event.currentTarget.getBoundingClientRect()
      const y = event.clientY - draggedRect.top

      // 找到最近的目标位置
      let closestIndex = 0
      let closestDistance = Infinity

      items.forEach((item, index) => {
        const rect = item.getBoundingClientRect()
        const distance = Math.abs(y - (rect.top - draggedRect.top + rect.height / 2))
        if (distance < closestDistance) {
          closestDistance = distance
          closestIndex = index
        }
      })

      return closestIndex
    }
  }
}
</script>

<style lang="scss">
.custom-dialog {
  position: fixed;
  right: 0;
  width: 600px;
  background: var(--bg-color);
  border-radius: 4px 0 0 4px;
  box-shadow: -2px 0 12px 0 rgba(0,0,0,.1);
  display: flex;
  flex-direction: column;
  z-index: 2001;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  border-bottom: 1px solid var(--border-color);
  user-select: none;
  background: var(--bg-color);

  span {
    font-size: 14px;
    color: var(--text-color);
    font-weight: 500;
  }

  .el-icon-close {
    font-size: 16px;
    color: var(--text-color-secondary);
    cursor: pointer;
    transition: color 0.2s;

    &:hover {
      color: var(--text-color);
    }
  }
}

.dialog-body {
  padding: 8px 12px;
  flex: 1;
  background: var(--bg-color);
}

.dialog-footer {
  padding: 8px 12px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  background: var(--bg-color);
}

.weld-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  height: 100%;
  user-select: none;
}

.available-cables {
  flex: 1;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  padding: 4px 0;
}

.button-group {
  display: flex;
  gap: 8px;
}

.transfer-btn {
  width: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  margin: 0;
}

.selected-cables {
  flex: 1;
  display: flex;
  gap: 8px;
}

.section-title {
  font-size: 13px;
  font-weight: bold;
  color: var(--text-color);
  margin-bottom: 4px;
}

.cable-list {
  border: 1px solid var(--border-color);
  border-radius: 4px;
  overflow-y: auto;
  background: var(--bg-color);
}

.cable-item {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  font-size: 12px;
  border-bottom: 1px solid var(--border-color-light);
  cursor: pointer;
  transition: all 0.2s;
  color: var(--text-color);
  user-select: none;

  &.dragging {
    background-color: var(--bg-hover-color);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }

  .drag-handle {
    cursor: move;
    color: var(--text-color-secondary);
    margin-right: 4px;
    font-size: 14px;
    opacity: 0;
    transition: all 0.2s;
  }

  &:hover {
    background-color: var(--bg-hover-color);

    .drag-handle {
      opacity: 1;
    }
  }

  &.is-selected {
    .theme-white & {
      color: #409eff;
      background-color: #ecf5ff;

      .cable-id {
        color: #409eff;
      }
    }

    .theme-black & {
      color: #fff;
      background-color: #409eff;

      .cable-id {
        color: #fff;
      }
    }
  }

  .cable-id {
    color: var(--text-color-secondary);
    width: 50%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding-right: 8px;
  }

  .cable-name {
    width: 50%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &:hover {
    .cable-id, .cable-name {
      position: relative;
      z-index: 1;
      background-color: var(--bg-hover-color);
    }
  }

  .el-icon-delete {
    color: #c0c4cc;
    cursor: pointer;
    padding: 4px;
    transition: all 0.2s;
    margin-left: auto;
    
    &:hover {
      color: #f56c6c;
    }
  }
}

.cable-section {
  flex: 1;
  min-width: 0; // 防止内容溢出
}
</style>
